package com.librelato.tela;

import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;

import org.primefaces.context.RequestContext;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

import com.librelato.bean.UsuarioBean;
import com.librelato.negocio.UsuarioServico;

@ManagedBean
@RequestScoped
public class IndexTela extends TelaAbstrata {

	@ManagedProperty(value = "#{usuario}")
	private UsuarioBean usuario;

	private UsuarioServico<UsuarioBean> servico = new UsuarioServico<UsuarioBean>();

	private StreamedContent file;

	public IndexTela() {
		InputStream stream = ((ServletContext) FacesContext
				.getCurrentInstance().getExternalContext().getContext())
				.getResourceAsStream("/download/ChromeSetup.exe");
		file = new DefaultStreamedContent(stream,
				"application/download","ChromeSetup.exe");
	}

	private boolean verificaNavegador() {
		boolean permite = true;

		String userAgent = FacesContext.getCurrentInstance()
				.getExternalContext().getRequestHeaderMap().get("User-Agent");
		Pattern pattern = Pattern.compile("MSIE");
		Matcher matcher = pattern.matcher(userAgent);
		if (matcher.find()) {
			String versao = userAgent.substring(userAgent.indexOf("MSIE") + 5,
					userAgent.indexOf("MSIE") + 6);
			int versaoNum = Integer.parseInt(versao.trim());
			if (versaoNum < 9 && versaoNum != 1) {
				permite = false;
			}
		}

		return permite;
	}

	public String logar() {

		if (verificaNavegador()) {

			FacesMessage msg = null;
			boolean enviado = false;
			String url = "/principal.xhtml?faces-redirect=true";
			try {
				usuario = this.getServico().logar(usuario);
				if (usuario != null) {
					if (usuario.getNome() != null) {
						if (usuario.getAtivo() != null
								&& usuario.getAtivo().equals("Sim")) {
							if (usuario.getListaEmpresas().size() != 0) {
								if (usuario.getListaMenus().size() != 0) {
									msg = new FacesMessage(
											FacesMessage.SEVERITY_INFO,
											this.getServico().getValor(
													"msg_header_sucesso"), this
													.getServico().getValor(
															"msg_body_sucesso"));
									enviado = true;
								} else {
									msg = new FacesMessage(
											FacesMessage.SEVERITY_WARN, this
													.getServico().getValor(
															"msg_header_erro"),
											this.getServico().getValor(
													"msg_body_erro_menu"));
									enviado = false;
								}
							} else {
								msg = new FacesMessage(
										FacesMessage.SEVERITY_WARN, this
												.getServico().getValor(
														"msg_header_erro"),
										this.getServico().getValor(
												"msg_body_erro_empresa"));
								enviado = false;
							}
						} else {
							msg = new FacesMessage(FacesMessage.SEVERITY_WARN,
									this.getServico().getValor(
											"msg_header_erro"), this
											.getServico().getValor(
													"msg_body_erro_ativo"));
							enviado = false;
						}
					} else {
						msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,
								this.getServico().getValor("msg_header_erro"),
								this.getServico().getValor("msg_body_erro"));
					}

				} else {
					msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, this
							.getServico().getValor("msg_header_erro"), this
							.getServico().getValor("msg_body_erro"));
				}
			} catch (Exception e) {
				msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, this
						.getServico().getValor("msg_header_erro"), this
						.getServico().getValor("msg_body_erro"));
				e.printStackTrace();
			}

			FacesContext.getCurrentInstance().addMessage(null, msg);

			return enviado ? url : null;

		} else {
			RequestContext.getCurrentInstance()
					.execute("barraNavegador.show()");
			return null;
		}
	}

	@Override
	protected UsuarioServico<UsuarioBean> getServico() {
		return servico;
	}

	public UsuarioBean getUsuario() {
		return usuario;
	}

	public void setUsuario(UsuarioBean usuario) {
		this.usuario = usuario;
	}

	public StreamedContent getFile() {
		return file;
	}

}
